package proj.unions.resource;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import proj.unions.general.L;
import proj.unions.general.OnMyCallBack;
import proj.unions.general.SuperTools;
import proj.unions.general.Text;
import proj.unions.resource.DownloadGameRes.FileData;
import android.accounts.NetworkErrorException;
import android.app.Activity;

public class DownloadGameLib implements Runnable, RMConstDefine {

	private static final int DOWNLOAD_STATUS_SUCCESSFUL = 1;
	private static final int DOWNLOAD_STATUS_NONE = 0;
	private static final int DOWNLOAD_STATUS_FAILURE_IO = -1;
	private static final int DOWNLOAD_STATUS_FAILURE_NET = -2;
	
	private Activity mActivity = null;
	private OnMyCallBack mOnMyCallBack = null;
	
	private String mSOUrl = null;
	private String mSoTempPath = null;
	private String mSoPath = null;
	
	private int mNewestVersion_lib = -1;
	
	private long lastSpeed = 0;//速度
	private long trunkSize = 0;//块大小
	private boolean isChange = false;
	private boolean isEndTimer = false;
	
	private int mCode = -1;
	private int mNeedDownloadCount = -1;
	private int mCountFile = -1;
	
	private JSONObject mJson = null;
	
	public DownloadGameLib(Activity a, OnMyCallBack l, JSONObject json)
	{
		mActivity = a;
		mOnMyCallBack = l;
		mJson = json;
		
		try {
			mSOUrl = json.getString(KEY_SO_URL);	//so文件地址
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		lastSpeed = 0;
		trunkSize = 0;
		isChange = false;
		isEndTimer = false;
		
		try {
			mNewestVersion_lib = mJson.getInt(KEY_NEWEST_VERSION_LIB);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String fileName = mSOUrl.substring(mSOUrl.lastIndexOf("/") + 1);
		mSoTempPath =  SuperTools.getInstance().getDownloadLibPath() + fileName;
//		mSoPath = SuperTools.getInstance().getDownloadLibPath();// + fileName.replace(".zip", ".so");
		mSoPath = SuperTools.getInstance().getSystemPath();
	}
	
	@Override
	public void run() {
		// TODO Auto-generated method stub
		if (mActivity == null || mOnMyCallBack == null)
		{
			mOnMyCallBack.onReceive("error", 0, null);
			return;
		}

		if(check())
		{
//			startTimer();
			String content = Text.getKey("Net_DownloadLib")/*"正在下载lib文件*/ + ":" + mNewestVersion_lib + ".lib";
			setTimer(true, content);	
			downloadFile(mSOUrl, mSoTempPath);
//			mOnMyCallBack.onReceive("", 2, null);
			setTimer(true, Text.getKey("Net_UnZipLib")/*"开始解压lib文件"*/);
			L.d("开始解压lib文件");
			if(unzipFile(mSoTempPath, mSoPath))
			{
				SuperTools.deleteFile(new File(mSoTempPath));
				SuperTools.getInstance().writeLocalFile(KEY_CLIENT_VERSION_LIB, "" + 
						mNewestVersion_lib);
				L.d("解压lib成功");
			}
			else
				L.d("解压lib失败");
		}

		setTimer(false, "");
		isEndTimer = true;
		mOnMyCallBack.onReceive("yes", 1, mJson);
	}
	
	//检测
	private boolean check()
	{
		boolean isUpdate = false;
		try {
			isUpdate = mJson.getBoolean(KEY_NEED_UPDATE_LIB);
			
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return isUpdate;
	}
	
	//下载
	private int downloadFile(String url, String name)
	{
		float retainLength = ResManager.mIamgeTotalength * 0.15f;
		float countPercent = ResManager.mCountPercent;
		
		try {
			byte[] buffer = new byte[2048];
			HttpGet getMethod = new HttpGet(url);
			HttpClient httpClient = new DefaultHttpClient();
			HttpResponse response = httpClient.execute(getMethod);
			
			long fileSize = response.getEntity().getContentLength();
			
			int byteReaded = 0;
			int curSize = 0;
			
			int code = response.getStatusLine().getStatusCode();
			if (code == 200) 
			{
				InputStream is = response.getEntity().getContent();
				File f = new File(name);
				if (f.exists())
					f.delete();
				if (!f.getParentFile().exists()) {
					f.getParentFile().mkdirs();
				}
				f.createNewFile();
				FileOutputStream fos = new FileOutputStream(f);
				
				do {
					try {
						byteReaded = is.read(buffer);
						curSize += byteReaded;
						trunkSize += byteReaded;
						float curProcess = ((float) curSize / (float) fileSize * 100);
						int count = (int) (curProcess / 2);
						if (isChange) {
							isChange = false;
							lastSpeed = trunkSize / 1024;
							trunkSize = 0;
						}
						
//						String content = "正在更新版本:" + mNewestVersion_lib + 
//								" 已下载  " + (curSize / 1024 ) + " / " + 
//								(fileSize / 1024 ) + "KB  速度" +
//										lastSpeed + "KB/s";
						
						float ret = ((float)curSize / (float)fileSize) * retainLength;
						ResManager.mCountPercent = countPercent + (ret / ResManager.mIamgeTotalength);
//						String content = "正在下载lib文件:" + mNewestVersion_lib + ".lib";	
//						mOnMyCallBack.onReceive(content, 2, null);

					} catch (IOException e) {
						try {
							throw new NetworkErrorException(e);
						} catch (NetworkErrorException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}
					}
					if (byteReaded > 0) {
						fos.write(buffer, 0, byteReaded);
					}
					fos.flush();
				} while (byteReaded != -1);
				fos.close();
				
				return DOWNLOAD_STATUS_SUCCESSFUL;
			}
			else
				mCode = code;
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			L.d("download:" + e.getMessage());
			return DOWNLOAD_STATUS_FAILURE_NET;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			L.d("download:" + e.getMessage());
			return DOWNLOAD_STATUS_FAILURE_IO;
		}

		return DOWNLOAD_STATUS_NONE;
	}
	
	
	//解压
	public static boolean unzipFile(String tpFileName, String tpFilePath)
	{
		String srcFileName = tpFileName;
		try {
			FileInputStream stream = new FileInputStream(srcFileName);
			try {
				java.util.zip.ZipInputStream inZip = new java.util.zip.ZipInputStream(stream);
				ZipEntry zipEntry = inZip.getNextEntry();
				
				String targetFileName = tpFilePath + zipEntry.getName();
				String TargetFileName_tp = tpFilePath + zipEntry.getName() + "_tp";
				File tpTargetFileName = new File(TargetFileName_tp);
				if ( tpTargetFileName.exists() )
					tpTargetFileName.delete();
				
				byte[] buffer = new byte[10240];
				try {
					FileOutputStream out = new java.io.FileOutputStream(TargetFileName_tp);
					int len;
					while ((len = inZip.read(buffer)) != -1) 
					{
						out.write(buffer, 0, len);
						out.flush();
					}
					
					out.close();
					
					//改回正常的名字
					File oldf = new File(TargetFileName_tp);
					File newf = new File(targetFileName);
					oldf.renameTo(newf);
					
					return true;
					
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}
	
	private void startTimer()
	{
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				try {
					while(!isEndTimer)
					{
						isChange =  true;
						Thread.sleep(400);
					}
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}).start();
	}
	
	private static Thread mTimerThread = null;
	private static String mTimerString = null; 
	//定时去处理下方文字
	private void setTimer(boolean _isOpen, String _content)
	{
		mTimerString = _content;
		if(mTimerThread == null)
			mTimerThread = new Thread(new Runnable() {
				
				@Override
				public void run() {
					// TODO Auto-generated method stub
					while (true)
					{
						if(Thread.currentThread().getName().equals("Over"))
							break;
						try {
							Thread.sleep(400);
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						String ret = mTimerString;
						if(!mTimerString.equals(""))
							ret += SuperTools.getInstance().getSomeThing(false);
						mOnMyCallBack.onReceive(ret, 2, null);
					}
					L.d("===== end DownloadGameLib Timer");
				}
			});
		
		if(_isOpen && mTimerThread != null)
		{
			SuperTools.getInstance().getSomeThing(true);
			if(!mTimerThread.isAlive())
				mTimerThread.start();
		}
		if(!_isOpen && mTimerThread != null)
		{
			mTimerThread.setName("Over");
			mTimerThread = null;
		}
	}
	
}
